package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.CommunityConstant;
import com.nowcoder.community.utils.CommunityUtil;
import com.nowcoder.community.utils.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    @Value("${community.path.domain}")
    private String domain;
@Value("${community.path.upload}")
private String upload;

@Value("${server.servlet.context-path}")
private String contextPath;

@Autowired
private HostHolder hostHolder;


private Logger logger= LoggerFactory.getLogger(UserController.class);

@Autowired
private UserService userService;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${quniu.bucket.header.url}")
    private String headerBucketUrl;

@GetMapping("/toSetting")
public String toSetting(Model model)
{
    // 上传文件名称
    String fileName = CommunityUtil.generateUUID();
    // 设置响应信息
    StringMap policy = new StringMap();
    policy.put("returnBody", CommunityUtil.getJSONString(0));
    // 生成上传凭证
    Auth auth = Auth.create(accessKey, secretKey);
    String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600, policy);

    model.addAttribute("uploadToken", uploadToken);
    model.addAttribute("fileName", fileName);


    return "site/setting";
}

    // 更新头像路径
    @RequestMapping(path = "/header/url", method = RequestMethod.POST)
    @ResponseBody
    public String updateHeaderUrl(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return CommunityUtil.getJSONString(1, "文件名不能为空!");
        }

        String url = headerBucketUrl + "/" + fileName;
        userService.updateHeader(hostHolder.getUser().getId(), url);

        return CommunityUtil.getJSONString(0);
    }
//废弃
    @LoginRequired
    @PostMapping("/setting")
    public String setting(MultipartFile headImage, Model model){
        if (headImage == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }

        String fileName = headImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件的格式不正确!");
            return "/site/setting";
        }

        // 生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;

      File dest=new File(upload+"/"+fileName);
        try {
            headImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("文件上传失败："+e.getMessage());
           throw new RuntimeException("上传文件失败，服务器异常",e);
        }

        //更新当前用户头像的路径
        // http://localhost:8080/community/user/header/filename
        User user = hostHolder.getUser();
        userService.updateHeader(user.getId(),domain+contextPath+"/user/header/"+fileName);



        return "redirect:/index";
    }

    //废弃
//向浏览器响应头像
    @RequestMapping("/header/{filename}")
    public void getHeader(HttpServletResponse response,@PathVariable("filename") String filename){
        try {
            FileInputStream fis=new FileInputStream(upload+"/"+filename);
            String suffix=filename.substring(filename.lastIndexOf('.'));

            response.setContentType("images/"+suffix);

            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes=new byte[1024];
            int len=0;
            while ((len=fis.read(bytes))!=-1){
                 outputStream.write(bytes,0,len);
            }
        } catch (FileNotFoundException e) {
           logger.error("文件找不到路径"+e.getMessage());
        } catch (IOException e) {
          logger.error("获取头像失败"+e.getMessage());
        }
    }


    @Autowired
    private LikeService likeService;


@Autowired
private FollowService followService;
    // 个人主页
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }

        // 用户
        model.addAttribute("user", user);
        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);


        //用户关注实体的数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);

        //用户粉丝的数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followeeCount",followeeCount);
        model.addAttribute("followerCount",followerCount);

        //是否关注
        boolean hasFollowee=false;
        if(hostHolder.getUser()!=null){
            hasFollowee=followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);

        }
        model.addAttribute("hasFollowee",hasFollowee);

        return "/site/profile";
    }

}
